import React, { useState, useEffect, useCallback } from 'react'
import { Card, Button, Space, Modal, message, Descriptions, Tag, Row, Col, Select, Input } from 'antd'
import { EyeOutlined, CheckOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import DataTable from '../../../components/common/DataTable'
import Form from '../../../components/common/Form'
import { listApplications, getApplication, reviewApplication } from '../../../api/application'

const { Option } = Select
const { TextArea } = Input

const Application = () => {
    const [loading, setLoading] = useState(false)
    const [dataSource, setDataSource] = useState([])
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    })
    const [viewVisible, setViewVisible] = useState(false)
    const [viewApplication, setViewApplication] = useState(null)
    const [reviewVisible, setReviewVisible] = useState(false)
    const [currentApplication, setCurrentApplication] = useState(null)

    // 获取应聘申请数据
    const fetchApplications = useCallback(async () => {
        setLoading(true)
        try {
            const params = {
                page: pagination.current,
                pageSize: pagination.pageSize
            }
            const res = await listApplications(params)
            setDataSource(res.data.items || [])
            setPagination(prev => ({
                ...prev,
                total: res.data.total || 0
            }))
        } catch (error) {
            message.error('获取应聘申请列表失败')
            console.error(error)
        } finally {
            setLoading(false)
        }
    }, [pagination.current, pagination.pageSize])

    useEffect(() => {
        fetchApplications()
    }, [fetchApplications])

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination)
    }

    // 处理搜索
    const handleSearch = async (value) => {
        setLoading(true)
        try {
            const params = {
                page: 1,
                pageSize: pagination.pageSize,
                keyword: value
            }
            const res = await listApplications(params)
            setDataSource(res.data.items || [])
            setPagination({
                ...pagination,
                current: 1,
                total: res.data.total || 0
            })
        } catch (error) {
            message.error('搜索失败')
            console.error(error)
        } finally {
            setLoading(false)
        }
    }

    // 查看申请详情
    const handleView = async (id) => {
        try {
            const res = await getApplication(id)
            setViewApplication(res.data)
            setViewVisible(true)
        } catch (error) {
            message.error('获取申请详情失败')
            console.error(error)
        }
    }

    // 审核申请
    const handleReview = (record) => {
        setCurrentApplication(record)
        setReviewVisible(true)
    }

    // 提交审核结果
    const handleReviewSubmit = async (values) => {
        try {
            await reviewApplication(currentApplication.id, values)
            message.success('审核成功')
            setReviewVisible(false)
            fetchApplications()
        } catch (error) {
            message.error('审核失败')
            console.error(error)
        }
    }

    // 获取状态标签颜色
    const getStatusColor = (status) => {
        switch (status) {
            case 0: return 'blue'    // 待审核
            case 1: return 'green'   // 通过
            case 2: return 'red'     // 拒绝
            default: return 'default'
        }
    }

    // 获取状态文本
    const getStatusText = (status) => {
        switch (status) {
            case 0: return '待审核'
            case 1: return '已通过'
            case 2: return '已拒绝'
            default: return '未知状态'
        }
    }

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80
        },
        {
            title: '应聘者',
            dataIndex: 'applicantName',
            key: 'applicantName'
        },
        {
            title: '应聘职位',
            dataIndex: 'positionName',
            key: 'positionName'
        },
        {
            title: '申请日期',
            dataIndex: 'applyDate',
            key: 'applyDate'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => (
                <Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
            )
        },
        {
            title: '操作',
            key: 'action',
            width: 180,
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="text" 
                        icon={<EyeOutlined />} 
                        onClick={() => handleView(record.id)}
                    >
                        查看
                    </Button>
                    {record.status === 0 && (
                        <Button 
                            type="text" 
                            icon={<CheckOutlined />} 
                            onClick={() => handleReview(record)}
                        >
                            审核
                        </Button>
                    )}
                </Space>
            )
        }
    ]

    return (
        <div className="application-container">
            <Card title="应聘申请管理">
                <DataTable 
                    columns={columns}
                    dataSource={dataSource}
                    loading={loading}
                    rowKey="id"
                    pagination={pagination}
                    onChange={handleTableChange}
                    onSearch={handleSearch}
                    onRefresh={fetchApplications}
                    searchPlaceholder="搜索应聘者/职位"
                />
            </Card>

            {/* 查看申请详情模态框 */}
            <Modal
                title="申请详情"
                open={viewVisible}
                onCancel={() => setViewVisible(false)}
                footer={null}
                width={700}
            >
                {viewApplication && (
                    <Descriptions bordered column={2}>
                        <Descriptions.Item label="应聘者" span={2}>{viewApplication.applicantName}</Descriptions.Item>
                        <Descriptions.Item label="应聘职位" span={2}>{viewApplication.positionName}</Descriptions.Item>
                        <Descriptions.Item label="申请日期">{viewApplication.applyDate}</Descriptions.Item>
                        <Descriptions.Item label="状态">
                            <Tag color={getStatusColor(viewApplication.status)}>
                                {getStatusText(viewApplication.status)}
                            </Tag>
                        </Descriptions.Item>
                        <Descriptions.Item label="联系电话">{viewApplication.phone}</Descriptions.Item>
                        <Descriptions.Item label="电子邮箱">{viewApplication.email}</Descriptions.Item>
                        <Descriptions.Item label="求职信" span={2}>
                            <div style={{ whiteSpace: 'pre-wrap' }}>{viewApplication.coverLetter}</div>
                        </Descriptions.Item>
                        {viewApplication.feedback && (
                            <Descriptions.Item label="反馈" span={2}>
                                <div style={{ whiteSpace: 'pre-wrap' }}>{viewApplication.feedback}</div>
                            </Descriptions.Item>
                        )}
                    </Descriptions>
                )}
            </Modal>

            {/* 审核申请模态框 */}
            <Modal
                title="审核申请"
                open={reviewVisible}
                onCancel={() => setReviewVisible(false)}
                footer={null}
            >
                <Form
                    onFinish={handleReviewSubmit}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name="status"
                        label="审核结果"
                        rules={[{ required: true, message: '请选择审核结果' }]}
                    >
                        <Select placeholder="请选择审核结果">
                            <Option value={1}>通过</Option>
                            <Option value={2}>拒绝</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="feedback"
                        label="反馈"
                        rules={[{ required: true, message: '请输入反馈' }]}
                    >
                        <TextArea rows={4} placeholder="请输入反馈" />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}

export default Application